<template>
  <div class="announcements-container">
    <el-card class="announcements-card">
      <template #header>
        <div class="card-header">
          <span>公告管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增公告
          </el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="公告标题">
              <el-input
                v-model="searchForm.title"
                placeholder="请输入公告标题"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="公告类型">
              <el-select
                v-model="searchForm.type"
                placeholder="请选择公告类型"
                clearable
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态">
              <el-select
                v-model="searchForm.status"
                placeholder="请选择状态"
                clearable
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: right">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>

      <!-- 公告表格 -->
      <el-table
        :data="announcementList"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="title" label="公告标题" min-width="200" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" width="160" />
        <el-table-column prop="expireTime" label="过期时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button
              v-if="row.status === 'draft'"
              type="success"
              link
              @click="handlePublish(row)"
            >
              发布
            </el-button>
            <el-button
              v-if="row.status === 'published'"
              type="warning"
              link
              @click="handleArchive(row)"
            >
              归档
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增公告' : '编辑公告'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="announcementForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="公告标题" prop="title">
          <el-input
            v-model="announcementForm.title"
            placeholder="请输入公告标题"
          />
        </el-form-item>
        <el-form-item label="公告类型" prop="type">
          <el-select v-model="announcementForm.type" placeholder="请选择公告类型">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="announcementForm.priority" placeholder="请选择优先级">
            <el-option
              v-for="item in priorityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input
            v-model="announcementForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入公告内容"
          />
        </el-form-item>
        <el-form-item label="过期时间">
          <el-date-picker
            v-model="announcementForm.expireTime"
            type="datetime"
            placeholder="选择过期时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAnnouncementPage,
  addAnnouncement,
  updateAnnouncement,
  deleteAnnouncement,
  publishAnnouncement,
  archiveAnnouncement,
  type AnnouncementData
} from '@/api/announcements'

const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const formRef = ref<FormInstance>()

const searchForm = reactive({
  title: '',
  type: '',
  status: '',
  priority: ''
})

const announcementForm = reactive({
  id: 0,
  title: '',
  content: '',
  type: 'notice' as 'notice' | 'news' | 'policy' | 'other',
  priority: 'medium' as 'low' | 'medium' | 'high',
  expireTime: ''
})

const rules = {
  title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
  type: [{ required: true, message: '请选择公告类型', trigger: 'change' }],
  priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
  content: [{ required: true, message: '请输入公告内容', trigger: 'blur' }]
}

const typeOptions = [
  { value: 'notice', label: '通知' },
  { value: 'news', label: '新闻' },
  { value: 'policy', label: '政策' },
  { value: 'other', label: '其他' }
]

const statusOptions = [
  { value: 'draft', label: '草稿' },
  { value: 'published', label: '已发布' },
  { value: 'archived', label: '已归档' }
]

const priorityOptions = [
  { value: 'low', label: '低' },
  { value: 'medium', label: '中' },
  { value: 'high', label: '高' }
]

const announcementList = ref<AnnouncementData[]>([])

function getTypeTag(type: string) {
  const map: Record<string, string> = {
    notice: 'primary',
    news: 'success',
    policy: 'warning',
    other: 'info'
  }
  return map[type] || 'info'
}

function getTypeText(type: string) {
  const map: Record<string, string> = {
    notice: '通知',
    news: '新闻',
    policy: '政策',
    other: '其他'
  }
  return map[type] || '未知'
}

function getPriorityTag(priority: string) {
  const map: Record<string, string> = {
    low: 'info',
    medium: 'primary',
    high: 'danger'
  }
  return map[priority] || 'info'
}

function getPriorityText(priority: string) {
  const map: Record<string, string> = {
    low: '低',
    medium: '中',
    high: '高'
  }
  return map[priority] || '未知'
}

function getStatusTag(status: string) {
  const map: Record<string, string> = {
    draft: 'info',
    published: 'success',
    archived: 'warning'
  }
  return map[status] || 'info'
}

function getStatusText(status: string) {
  const map: Record<string, string> = {
    draft: '草稿',
    published: '已发布',
    archived: '已归档'
  }
  return map[status] || '未知'
}

async function loadAnnouncements() {
  loading.value = true
  try {
    const response = await getAnnouncementPage({
      current: currentPage.value,
      size: pageSize.value,
      title: searchForm.title,
      type: searchForm.type,
      status: searchForm.status,
      priority: searchForm.priority
    })
    
    announcementList.value = response.records || []
    total.value = response.total || 0
  } catch (error) {
    console.error('获取公告列表失败:', error)
    ElMessage.error('获取公告列表失败')
    announcementList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  currentPage.value = 1
  loadAnnouncements()
}

function handleReset() {
  Object.assign(searchForm, {
    title: '',
    type: '',
    status: '',
    priority: ''
  })
  handleSearch()
}

function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(announcementForm, {
    id: 0,
    title: '',
    content: '',
    type: 'notice',
    priority: 'medium',
    expireTime: ''
  })
}

function handleAdd() {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

function handleEdit(row: AnnouncementData) {
  dialogType.value = 'edit'
  Object.assign(announcementForm, {
    id: row.id,
    title: row.title,
    content: row.content,
    type: row.type,
    priority: row.priority,
    expireTime: row.expireTime
  })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const formData = {
      title: announcementForm.title,
      content: announcementForm.content,
      type: announcementForm.type,
      priority: announcementForm.priority,
      expireTime: announcementForm.expireTime,
      status: 'draft' as const
    }
    
    if (dialogType.value === 'add') {
      await addAnnouncement(formData)
      ElMessage.success('新增成功')
    } else {
      await updateAnnouncement({ ...formData, id: announcementForm.id } as AnnouncementData)
      ElMessage.success('编辑成功')
    }
    
    dialogVisible.value = false
    loadAnnouncements()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(dialogType.value === 'add' ? '新增失败' : '编辑失败')
  }
}

function handlePublish(row: AnnouncementData) {
  ElMessageBox.confirm(
    '确认发布该公告吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      publishAnnouncement(row.id)
        .then(() => {
          ElMessage.success('发布成功')
          loadAnnouncements()
        })
        .catch(() => {
          ElMessage.error('发布失败')
        })
    })
    .catch(() => {
      ElMessage.info('已取消发布')
    })
}

function handleArchive(row: AnnouncementData) {
  ElMessageBox.confirm(
    '确认归档该公告吗？归档后将不再显示',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      archiveAnnouncement(row.id)
        .then(() => {
          ElMessage.success('归档成功')
          loadAnnouncements()
        })
        .catch(() => {
          ElMessage.error('归档失败')
        })
    })
    .catch(() => {
      ElMessage.info('已取消归档')
    })
}

function handleDelete(row: AnnouncementData) {
  ElMessageBox.confirm(
    '确定要删除该公告吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      deleteAnnouncement(row.id)
        .then(() => {
          ElMessage.success('删除成功')
          loadAnnouncements()
        })
        .catch(() => {
          ElMessage.error('删除失败')
        })
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

function handleSizeChange(val: number) {
  pageSize.value = val
  loadAnnouncements()
}

function handleCurrentChange(val: number) {
  currentPage.value = val
  loadAnnouncements()
}

onMounted(() => {
  loadAnnouncements()
})
</script>

<style scoped>
.announcements-container {
  padding: 20px;
}

.announcements-card {
  background: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: var(--el-fill-color-blank);
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>